const { useState, useRef, useEffect } = React;
const { Button,  Col, Row, Card } = antd;

const MonacoEditor = () => {
  const [editor, setEditor] = useState(null);
  const [html, setHtml] = useState('');

  useEffect(() => {
    const loadMonaco = async () => {
        require.config({ paths: { 'vs': 'http://localhost:8787/monaco-editor/min/vs' }});
        require(['vs/editor/editor.main'], function() {
            const init_doc = '# Hello Monaco\n\nThis is a markdown preview.'
            var editor = monaco.editor.create(document.getElementById('container'), {
                value: init_doc,
                language: 'markdown'
            });
    

            setEditor(editor)
            updateMd(init_doc)

            editor.onDidChangeModelContent(function(event) {
                //console.log('Model content changed:', event);
            });

            editor.onKeyDown(function (e) {
                if (e.keyCode === monaco.KeyCode.Enter && !e.shiftKey) { // 当按下 Enter 键且不是 Shift + Enter
                    var model = editor.getModel();
                    var position = editor.getPosition();
                    var lineContent = model.getLineContent(position.lineNumber);
                    var lineLength = lineContent.length+1;

                    // 检查当前行是否是列表项
                    var isList = lineContent.trim().startsWith('-');

                    if (isList) {
                        console.log('isList', isList, position.column , lineLength)
                        if (position.column === lineLength) {
                            var newLineContent = '\n- ';
                            model.pushEditOperations(
                                null,
                                [{
                                    range: new monaco.Range(position.lineNumber + 1, 1, position.lineNumber + 1, 1),
                                    text: newLineContent
                                }],
                                function () { return []; }
                            );
                            e.preventDefault();
                        }
                    }
                }
            });


        });
    };

    loadMonaco();
  }, []);

  useEffect(() => {
    if (editor) {
      const dispose = editor.onDidChangeModelContent(() => {
        const doc = editor.getValue()
        //console.log('doc:', doc);
        updateMd(doc)
      });

      return () => dispose.dispose();
    }
  }, [editor]);

  const updateMd = (doc) => {
      const htmlOutput = marked.parse(doc);
      setHtml(htmlOutput)
  }

  return (
    <Row>
      <Col span={12}>
        <div id="container" style={{ height: '600px', width: '100%' }} />
      </Col>
      <Col span={12}>
        <Card style={{width: '98%', }} >
          <div dangerouslySetInnerHTML={{ __html: html }} />
        </Card>      
      </Col>
    </Row>
  );
};